<template>
  <div class="atomic-db-task-container">
    <el-card class="task-header-card">
      <div class="task-header">
        <div class="task-title">
          <h2>{{ task.name }}</h2>
          <el-tag :type="getStatusType(task.status)" size="small">{{ task.status }}</el-tag>
        </div>
        <div class="task-actions">
          <el-button-group>
            <el-button type="primary" size="small" @click="goBack">
              <el-icon><Back /></el-icon> 返回
            </el-button>
            <el-button type="success" size="small" @click="markAsCompleted" :disabled="isTaskCompleted">
              <el-icon><Check /></el-icon> 标记完成
            </el-button>
          </el-button-group>
        </div>
      </div>
      
      <div class="task-info">
        <div class="info-item">
          <span class="label">任务ID:</span>
          <span>{{ task.id }}</span>
        </div>
        <div class="info-item">
          <span class="label">创建时间:</span>
          <span>{{ formatDate(task.created_at) }}</span>
        </div>
        <div class="info-item">
          <span class="label">截止时间:</span>
          <span>{{ formatDate(task.due_date) }}</span>
        </div>
        <div class="info-item">
          <span class="label">预计工时:</span>
          <span>{{ task.estimated_hours }} 小时</span>
        </div>
        <div class="info-item">
          <span class="label">分配给:</span>
          <span>{{ task.assigned_to || '未分配' }}</span>
        </div>
        <div class="info-item db-connection-item">
          <span class="label">数据库连接:</span>
          <span>
            <template v-if="task.project && task.project.database_connections && task.project.database_connections.length">
              <el-tag 
                v-for="conn in task.project.database_connections.slice(0, 3)" 
                :key="conn.id"
                size="small" 
                type="success" 
                class="db-tag"
              >
                {{ conn.name }}
              </el-tag>
              <el-tag v-if="task.project.database_connections.length > 3" size="small" type="info">
                +{{ task.project.database_connections.length - 3 }}
              </el-tag>
            </template>
            <template v-else>
              <el-tag size="small" type="warning">未设置数据库连接</el-tag>
            </template>
          </span>
        </div>
      </div>
      
      <div class="task-description">
        <h3>任务描述</h3>
        <div v-html="renderedDescription" class="description-content"></div>
      </div>
      
      <div class="task-actions-secondary">
        <el-button type="primary" size="small" @click="showBreakdownVersions">
          <el-icon><Document /></el-icon> 管理拆分版本
        </el-button>
      </div>
    </el-card>
    
    <el-alert
      v-if="!hasActiveBreakdownVersion"
      title="任务没有活跃的拆分版本，请先创建或激活拆分版本"
      type="warning"
      :closable="false"
      style="margin-bottom: 20px;"
    />
    
    <el-divider content-position="center">数据库操作</el-divider>
    
    <DatabaseOperations 
      :taskId="taskId"
      :projectId="projectId"
      @db-operation-completed="handleDbOperationCompleted"
    />
    
    <!-- 显示子任务列表 -->
    <el-divider content-position="center">子任务</el-divider>
    
    <el-card v-if="task.subtasks && task.subtasks.length" class="subtasks-card">
      <el-tree
        :data="task.subtasks"
        :props="{
          children: 'children',
          label: 'title'
        }"
        node-key="id"
        default-expand-all
      >
        <template #default="{ node, data }">
          <div class="subtask-node">
            <span class="subtask-title">{{ data.title }}</span>
            <span v-if="data.description" class="subtask-description">{{ data.description }}</span>
            <el-tag size="small" :type="getStatusType(data.status)">{{ data.status }}</el-tag>
            <span v-if="data.estimated_hours" class="subtask-hours">
              {{ data.estimated_hours }}小时
            </span>
            <el-tag v-if="data.is_atomic" size="small" type="success">原子任务</el-tag>
          </div>
        </template>
      </el-tree>
    </el-card>
    <el-empty v-else description="暂无子任务" />
    
    <el-divider content-position="center">执行记录</el-divider>
    
    <el-card class="execution-history-card" v-loading="isLoadingExecutions">
      <el-table :data="executionHistory" stripe style="width: 100%">
        <el-table-column prop="action" label="操作类型" min-width="120">
          <template #default="scope">
            <el-tag :type="getExecutionActionType(scope.row.action)">
              {{ getExecutionActionName(scope.row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="created_at" label="执行时间" min-width="150">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getExecutionStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="executed_by" label="执行人" min-width="120" />
        <el-table-column label="操作" min-width="150">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewExecutionDetails(scope.row)">
              详情
            </el-button>
            <el-button 
              v-if="scope.row.review_status !== 'APPROVED'"
              size="small" 
              type="success" 
              @click="markExecutionAsReviewed(scope.row.id)"
            >
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="!executionHistory.length" description="暂无执行记录" />
    </el-card>
    
    <!-- 执行详情对话框 -->
    <el-dialog
      v-model="executionDetailsDialogVisible"
      title="执行详情"
      width="70%"
    >
      <div v-if="selectedExecution" class="execution-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ selectedExecution.id }}</el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getExecutionActionType(selectedExecution.action)">
              {{ getExecutionActionName(selectedExecution.action) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行时间">{{ formatDate(selectedExecution.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getExecutionStatusType(selectedExecution.status)">
              {{ selectedExecution.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行人">{{ selectedExecution.executed_by }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getReviewStatusType(selectedExecution.review_status)">
              {{ selectedExecution.review_status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-tabs v-model="executionDetailsTab" class="execution-tabs">
          <el-tab-pane label="执行结果" name="result">
            <div v-if="selectedExecution.result" class="execution-result">
              <div v-if="typeof selectedExecution.result === 'object'" class="result-object">
                <div v-if="selectedExecution.action.startsWith('db_query')">
                  <h4>SQL 查询</h4>
                  <pre>{{ selectedExecution.result.sql }}</pre>
                  
                  <template v-if="selectedExecution.result.success">
                    <h4>结果</h4>
                    <el-table 
                      v-if="selectedExecution.result.data && selectedExecution.result.data.length" 
                      :data="selectedExecution.result.data" 
                      border 
                      style="width: 100%"
                    >
                      <el-table-column
                        v-for="column in selectedExecution.result.columns"
                        :key="column"
                        :prop="column"
                        :label="column"
                        min-width="150"
                        show-overflow-tooltip
                      />
                    </el-table>
                    <el-empty v-else description="查询没有返回数据" />
                  </template>
                  
                  <template v-else>
                    <h4>错误信息</h4>
                    <div class="error-message">{{ selectedExecution.result.error }}</div>
                  </template>
                </div>
                
                <div v-else-if="selectedExecution.action.startsWith('db_update')">
                  <h4>SQL 执行</h4>
                  <pre>{{ selectedExecution.result.sql }}</pre>
                  
                  <template v-if="selectedExecution.result.success">
                    <h4>执行结果</h4>
                    <p>影响行数: {{ selectedExecution.result.rows_affected }}</p>
                  </template>
                  
                  <template v-else>
                    <h4>错误信息</h4>
                    <div class="error-message">{{ selectedExecution.result.error }}</div>
                  </template>
                </div>
                
                <pre v-else>{{ JSON.stringify(selectedExecution.result, null, 2) }}</pre>
              </div>
              <pre v-else>{{ selectedExecution.result }}</pre>
            </div>
            <el-empty v-else description="没有执行结果" />
          </el-tab-pane>
          
          <el-tab-pane label="备注" name="comments">
            <div class="execution-comments">
              <div v-if="selectedExecution.comments && selectedExecution.comments.length">
                <div v-for="(comment, index) in selectedExecution.comments" :key="index" class="comment-item">
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.author }}</span>
                    <span class="comment-time">{{ formatDate(comment.created_at) }}</span>
                  </div>
                  <div class="comment-content">{{ comment.content }}</div>
                </div>
              </div>
              <el-empty v-else description="暂无备注" />
              
              <div class="add-comment">
                <el-input
                  v-model="newComment"
                  type="textarea"
                  :rows="3"
                  placeholder="添加备注..."
                />
                <el-button type="primary" @click="addComment" :disabled="!newComment.trim()">
                  添加备注
                </el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
    
    <!-- 拆分版本管理对话框 -->
    <el-dialog
      v-model="breakdownDialogVisible"
      title="任务拆分版本管理"
      width="650px"
    >
      <div v-loading="isLoadingVersions">
        <div class="version-header">
          <h3>任务拆分版本列表</h3>
          <el-button type="primary" size="small" @click="showCreateVersionDialog">
            创建新版本
          </el-button>
        </div>
        
        <el-table :data="breakdownVersions" style="width: 100%">
          <el-table-column prop="version_number" label="版本号" width="80">
            <template #default="scope">
              V{{ scope.row.version_number }}
            </template>
          </el-table-column>
          <el-table-column prop="created_by" label="创建者" width="100"></el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                {{ scope.row.status === 'active' ? '活跃' : '归档' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="total_subtasks" label="子任务数" width="80"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small"
                @click="viewVersionDetail(scope.row.id)"
              >
                查看
              </el-button>
              <el-button 
                v-if="scope.row.status !== 'active'"
                type="success" 
                size="small"
                @click="activateVersion(scope.row.id)"
              >
                激活
              </el-button>
              <el-button 
                v-if="scope.row.status !== 'active'"
                type="danger" 
                size="small"
                @click="confirmDeleteVersion(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="breakdownVersions.length === 0 && !isLoadingVersions" class="no-versions">
          <p>暂无拆分版本，请点击"创建新版本"按钮创建</p>
        </div>
      </div>
    </el-dialog>
    
    <!-- 创建新版本对话框 -->
    <el-dialog
      v-model="createVersionDialogVisible"
      title="创建新的拆分版本"
      width="500px"
    >
      <el-form :model="newVersionForm" label-width="120px">
        <el-form-item label="创建方式">
          <el-radio-group v-model="newVersionForm.createMethod">
            <el-radio label="manual">手动创建</el-radio>
            <el-radio label="ai">AI辅助创建</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="newVersionForm.createMethod === 'ai'" label="AI提示词">
          <el-input
            v-model="newVersionForm.aiPrompt"
            type="textarea"
            :rows="4"
            placeholder="请输入提示词，引导AI拆分任务..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span>
          <el-button @click="createVersionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createVersion" :loading="isCreatingVersion">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { marked } from 'marked';
import { Back, Check, Document } from '@element-plus/icons-vue';
import DatabaseOperations from '../../components/DatabaseOperations.vue';
import { getTaskDetail, updateTask } from '../../api/taskService';
import { getTaskExecutions, updateTaskExecution } from '../../api/executionService';
import { 
  getTaskBreakdownVersions, 
  updateBreakdownVersionStatus, 
  manualBreakdownTask, 
  getBreakdownVersionDetail,
  activateBreakdownVersion,
  deleteBreakdownVersion 
} from '../../api/taskService';

export default {
  name: 'DatabaseTaskDetail',
  components: {
    Back,
    Check,
    DatabaseOperations,
    Document
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    
    // 从路由参数获取taskId
    const taskId = computed(() => Number(route.params.id));
    
    // 任务数据
    const task = ref({
      id: '',
      name: '',
      description: '',
      status: '',
      due_date: null,
      estimated_hours: 0,
      assigned_to: '',
      project: null,
      created_at: null
    });
    
    const projectId = computed(() => task.value.project?.id || null);
    
    // UI 状态
    const isLoading = ref(false);
    const isLoadingExecutions = ref(false);
    const executionHistory = ref([]);
    const selectedExecution = ref(null);
    const executionDetailsDialogVisible = ref(false);
    const executionDetailsTab = ref('result');
    const newComment = ref('');
    const breakdownDialogVisible = ref(false);
    const createVersionDialogVisible = ref(false);
    const newVersionForm = ref({
      createMethod: 'manual',
      aiPrompt: ''
    });
    const isCreatingVersion = ref(false);
    const breakdownVersions = ref([]);
    const isLoadingVersions = ref(false);
    const hasActiveBreakdownVersion = ref(true); // Assuming a default value
    
    // 计算属性
    const isTaskCompleted = computed(() => {
      return task.value.status === 'COMPLETED' || task.value.status === 'REVIEWED';
    });
    
    const renderedDescription = computed(() => {
      if (!task.value.description) return '';
      return marked(task.value.description);
    });
    
    // 方法
    const loadTaskDetail = async () => {
      if (!taskId.value) return;
      
      isLoading.value = true;
      try {
        const response = await getTaskDetail(taskId.value);
        
        if (response.data.status === 'success') {
          task.value = response.data.data || {};
          hasActiveBreakdownVersion.value = !!task.value.breakdown_version;
        } else {
          ElMessage.error(response.data.message || '获取任务详情失败');
        }
      } catch (error) {
        console.error('加载任务详情失败:', error);
        ElMessage.error(`加载任务详情失败: ${error.message || '未知错误'}`);
        
        // 开发测试数据
        task.value = {
          id: taskId.value,
          name: '示例数据库操作任务',
          description: '这是一个示例数据库操作任务，用于测试数据库操作功能。\n\n- 测试查询\n- 测试更新\n- 测试表结构',
          status: 'IN_PROGRESS',
          due_date: new Date(),
          estimated_hours: 4,
          assigned_to: '开发者',
          created_at: new Date(),
          project: {
            id: 1,
            name: '示例项目',
            database_connections: [
              { id: 1, name: 'MySQL开发环境' },
              { id: 2, name: 'MySQL测试环境' }
            ]
          }
        };
      } finally {
        isLoading.value = false;
      }
    };
    
    const loadExecutionHistory = async () => {
      if (!taskId.value) return;
      
      isLoadingExecutions.value = true;
      try {
        const response = await getTaskExecutions(taskId.value);
        
        if (response.data.success) {
          executionHistory.value = response.data.executions || [];
          
          // 过滤只显示数据库相关的操作
          executionHistory.value = executionHistory.value.filter(exec => 
            exec.action.startsWith('db_')
          );
        } else {
          ElMessage.error(response.data.message || '获取执行历史失败');
        }
      } catch (error) {
        console.error('加载执行历史失败:', error);
        ElMessage.error(`加载执行历史失败: ${error.message || '未知错误'}`);
        
        // 开发测试数据
        executionHistory.value = [
          {
            id: 1,
            action: 'db_query',
            description: 'SELECT * FROM users LIMIT 10',
            created_at: new Date(),
            status: 'SUCCESS',
            executed_by: '开发者',
            review_status: 'PENDING',
            result: {
              sql: 'SELECT * FROM users LIMIT 10',
              success: true,
              data: [
                { id: 1, username: 'user1', email: 'user1@example.com' },
                { id: 2, username: 'user2', email: 'user2@example.com' }
              ],
              columns: ['id', 'username', 'email']
            }
          },
          {
            id: 2,
            action: 'db_update',
            description: 'UPDATE users SET email = ? WHERE id = ?',
            created_at: new Date(Date.now() - 24 * 60 * 60 * 1000),
            status: 'SUCCESS',
            executed_by: '开发者',
            review_status: 'APPROVED',
            result: {
              sql: "UPDATE users SET email = 'new@example.com' WHERE id = 1",
              success: true,
              rows_affected: 1
            }
          }
        ];
      } finally {
        isLoadingExecutions.value = false;
      }
    };
    
    const markAsCompleted = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要将此任务标记为已完成吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        const updateData = {
          status: 'COMPLETED'
        };
        
        const response = await updateTask(taskId.value, updateData);
        
        if (response.data.success) {
          ElMessage.success('任务已标记为完成');
          loadTaskDetail();
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('更新任务状态失败:', error);
          ElMessage.error('更新任务状态失败');
        }
      }
    };
    
    const handleDbOperationCompleted = (result) => {
      // 记录数据库操作
      console.log('数据库操作完成:', result);
      
      // 刷新执行历史
      loadExecutionHistory();
    };
    
    const viewExecutionDetails = (execution) => {
      selectedExecution.value = execution;
      executionDetailsTab.value = 'result';
      executionDetailsDialogVisible.value = true;
    };
    
    const markExecutionAsReviewed = async (executionId) => {
      try {
        await ElMessageBox.confirm(
          '确定要将此执行标记为已审核吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        const updateData = {
          review_status: 'APPROVED'
        };
        
        const response = await updateTaskExecution(executionId, updateData);
        
        if (response.data.success) {
          ElMessage.success('执行已标记为已审核');
          loadExecutionHistory();
          
          if (selectedExecution.value && selectedExecution.value.id === executionId) {
            selectedExecution.value.review_status = 'APPROVED';
          }
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('更新执行状态失败:', error);
          ElMessage.error('更新执行状态失败');
        }
      }
    };
    
    const addComment = async () => {
      if (!selectedExecution.value || !newComment.value.trim()) return;
      
      try {
        const comment = {
          content: newComment.value,
          author: '当前用户', // 实际应从用户状态获取
          created_at: new Date()
        };
        
        // 模拟API调用
        // const response = await addExecutionComment(selectedExecution.value.id, comment);
        
        // 临时模拟处理
        if (!selectedExecution.value.comments) {
          selectedExecution.value.comments = [];
        }
        
        selectedExecution.value.comments.push(comment);
        newComment.value = '';
        
        ElMessage.success('备注已添加');
      } catch (error) {
        console.error('添加备注失败:', error);
        ElMessage.error('添加备注失败');
      }
    };
    
    const goBack = () => {
      router.back();
    };
    
    // 辅助函数
    const formatDate = (dateString) => {
      if (!dateString) return '未设置';
      
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    const getStatusType = (status) => {
      const statusMap = {
        'TODO': 'info',
        'IN_PROGRESS': 'warning',
        'COMPLETED': 'success',
        'REVIEWED': 'success',
        'BLOCKED': 'danger'
      };
      
      return statusMap[status] || 'info';
    };
    
    const getExecutionStatusType = (status) => {
      const statusMap = {
        'SUCCESS': 'success',
        'FAILED': 'danger',
        'PENDING': 'info',
        'IN_PROGRESS': 'warning'
      };
      
      return statusMap[status] || 'info';
    };
    
    const getReviewStatusType = (status) => {
      const statusMap = {
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'PENDING': 'info'
      };
      
      return statusMap[status] || 'info';
    };
    
    const getExecutionActionType = (action) => {
      const actionMap = {
        'db_query': 'info',
        'db_update': 'warning',
        'db_create': 'success',
        'db_alter': 'warning',
        'db_drop': 'danger'
      };
      
      for (const [key, value] of Object.entries(actionMap)) {
        if (action.startsWith(key)) {
          return value;
        }
      }
      
      return 'info';
    };
    
    const getExecutionActionName = (action) => {
      const actionMap = {
        'db_query': '数据库查询',
        'db_update': '数据库更新',
        'db_create': '创建表',
        'db_alter': '修改表',
        'db_drop': '删除表'
      };
      
      for (const [key, value] of Object.entries(actionMap)) {
        if (action.startsWith(key)) {
          return value;
        }
      }
      
      return action;
    };
    
    const showBreakdownVersions = () => {
      breakdownDialogVisible.value = true;
    };
    
    const loadBreakdownVersions = async () => {
      isLoadingVersions.value = true;
      try {
        const response = await getTaskBreakdownVersions(taskId.value);
        
        if (response.data.status === 'success') {
          breakdownVersions.value = response.data.data || [];
          hasActiveBreakdownVersion.value = breakdownVersions.value.some(v => v.status === 'active');
        } else {
          ElMessage.error(response.data.message || '获取拆分版本失败');
        }
      } catch (error) {
        console.error('加载拆分版本失败:', error);
        ElMessage.error(`加载拆分版本失败: ${error.message || '未知错误'}`);
      } finally {
        isLoadingVersions.value = false;
      }
    };
    
    const viewVersionDetail = (versionId) => {
      // 开始加载
      ElMessage.info('正在加载版本详情...');
      
      // 获取版本详情
      getBreakdownVersionDetail(versionId).then(response => {
        if (response.data.status === 'success') {
          const version = response.data.data;
          const subtasks = version.subtasks || [];
          
          // 生成子任务HTML
          let subtasksHtml = '';
          if (subtasks.length > 0) {
            subtasksHtml += '<div class="version-subtasks"><h4>子任务列表</h4><ul>';
            const renderSubtask = (task, level = 0) => {
              const indent = '&nbsp;'.repeat(level * 4);
              subtasksHtml += `<li>${indent}${task.title}`;
              if (task.status) {
                const statusClass = task.status === 'completed' ? 'success' : 
                                    task.status === 'in_progress' ? 'warning' : 'info';
                subtasksHtml += ` <span class="status-tag ${statusClass}">${task.status}</span>`;
              }
              subtasksHtml += '</li>';
              
              if (task.children && task.children.length > 0) {
                subtasksHtml += '<ul>';
                task.children.forEach(child => renderSubtask(child, level + 1));
                subtasksHtml += '</ul>';
              }
            };
            
            subtasks.forEach(task => renderSubtask(task));
            subtasksHtml += '</ul></div>';
          } else {
            subtasksHtml = '<p>该版本没有子任务</p>';
          }
          
          const contentHtml = `
            <div class="version-detail-content">
              <h3>版本 V${version.version_number}</h3>
              <p><strong>创建时间:</strong> ${formatDate(version.created_at)}</p>
              <p><strong>创建者:</strong> ${version.created_by}</p>
              <p><strong>状态:</strong> ${version.status === 'active' ? '活跃' : '归档'}</p>
              <p><strong>子任务数量:</strong> ${subtasks.length}</p>
              ${subtasksHtml}
            </div>
          `;
          
          // 使用ElMessageBox显示详情
          ElMessageBox.alert(
            contentHtml,
            '拆分版本详情',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '关闭'
            }
          );
        } else {
          ElMessageBox.alert(
            '加载版本详情失败',
            '错误',
            {
              type: 'error',
              confirmButtonText: '关闭'
            }
          );
        }
      }).catch(error => {
        console.error('获取版本详情失败:', error);
        ElMessageBox.alert(
          '获取版本详情失败: ' + (error.message || '未知错误'),
          '错误',
          {
            type: 'error',
            confirmButtonText: '关闭'
          }
        );
      });
    };
    
    const createVersion = async () => {
      isCreatingVersion.value = true;
      try {
        // 为手动创建任务准备任务结构
        const tasksData = {
          tasks: [
            {
              title: '示例子任务',
              description: '请修改此子任务或添加更多子任务',
              is_atomic: false,
              estimated_hours: 2,
              children: []
            }
          ]
        };
        
        const response = await manualBreakdownTask(taskId.value, tasksData);
        
        if (response.data.status === 'success') {
          ElMessage.success('新拆分版本已创建');
          await loadBreakdownVersions();
          createVersionDialogVisible.value = false;
        } else {
          ElMessage.error(response.data.message || '创建拆分版本失败');
        }
      } catch (error) {
        console.error('创建拆分版本失败:', error);
        ElMessage.error(`创建拆分版本失败: ${error.message || '未知错误'}`);
      } finally {
        isCreatingVersion.value = false;
      }
    };
    
    const showCreateVersionDialog = () => {
      newVersionForm.value = {
        createMethod: 'manual',
        aiPrompt: ''
      };
      createVersionDialogVisible.value = true;
    };
    
    const activateVersion = async (versionId) => {
      try {
        await ElMessageBox.confirm(
          '确定要将此版本激活吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        const response = await activateBreakdownVersion(versionId);
        
        if (response.data.status === 'success') {
          ElMessage.success('版本已激活');
          await loadBreakdownVersions();
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('激活版本失败:', error);
          ElMessage.error('激活版本失败');
        }
      }
    };
    
    const confirmDeleteVersion = async (version) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除版本 V${version.version_number} 吗？此操作不可逆。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        const response = await deleteBreakdownVersion(version.id);
        
        if (response.data.status === 'success') {
          ElMessage.success('版本已删除');
          await loadBreakdownVersions();
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除版本失败:', error);
          ElMessage.error('删除版本失败');
        }
      }
    };
    
    // 生命周期钩子
    onMounted(() => {
      loadTaskDetail();
      loadExecutionHistory();
      loadBreakdownVersions();
    });
    
    return {
      taskId,
      task,
      projectId,
      isLoading,
      isLoadingExecutions,
      executionHistory,
      isTaskCompleted,
      renderedDescription,
      selectedExecution,
      executionDetailsDialogVisible,
      executionDetailsTab,
      newComment,
      breakdownDialogVisible,
      createVersionDialogVisible,
      newVersionForm,
      isCreatingVersion,
      breakdownVersions,
      isLoadingVersions,
      hasActiveBreakdownVersion,
      loadTaskDetail,
      loadExecutionHistory,
      markAsCompleted,
      handleDbOperationCompleted,
      viewExecutionDetails,
      markExecutionAsReviewed,
      addComment,
      goBack,
      formatDate,
      getStatusType,
      getExecutionStatusType,
      getReviewStatusType,
      getExecutionActionType,
      getExecutionActionName,
      showBreakdownVersions,
      loadBreakdownVersions,
      viewVersionDetail,
      createVersion,
      showCreateVersionDialog,
      activateVersion,
      confirmDeleteVersion
    };
  }
};
</script>

<style scoped>
.atomic-db-task-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.task-header-card {
  margin-bottom: 20px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 15px;
}

.task-title h2 {
  margin: 0;
}

.task-info {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.db-connection-item {
  grid-column: span 3;
}

.db-tag {
  margin-right: 5px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.label {
  font-weight: bold;
  color: #606266;
}

.task-description {
  margin-top: 20px;
}

.description-content {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.execution-history-card {
  margin-top: 20px;
}

.execution-details {
  margin-top: 15px;
}

.execution-tabs {
  margin-top: 20px;
}

.execution-result {
  margin-top: 10px;
}

.error-message {
  color: #f56c6c;
  margin: 10px 0;
}

.execution-comments {
  margin-top: 10px;
}

.comment-item {
  padding: 10px;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 10px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.comment-author {
  font-weight: bold;
}

.comment-time {
  color: #909399;
  font-size: 0.9em;
}

.add-comment {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

pre {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  white-space: pre-wrap;
  overflow-x: auto;
  font-family: monospace;
}

.version-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.version-header h3 {
  margin: 0;
}

.subtasks-card {
  margin-bottom: 20px;
}

.subtask-node {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px 0;
}

.subtask-title {
  font-weight: 500;
}

.subtask-description {
  color: #606266;
  font-size: 0.9em;
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.subtask-hours {
  color: #909399;
  font-size: 0.9em;
}

.no-versions {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.task-actions-secondary {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.version-detail-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.version-detail-content h4 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #303133;
}

.version-detail-content p {
  margin: 8px 0;
}

.version-subtasks {
  margin-top: 20px;
}

.version-subtasks ul {
  padding-left: 20px;
  margin: 5px 0;
}

.version-subtasks li {
  padding: 5px 0;
  list-style-type: disc;
}

.status-tag {
  display: inline-block;
  padding: 2px 6px;
  font-size: 12px;
  border-radius: 3px;
  margin-left: 5px;
}

.status-tag.success {
  background-color: #67c23a;
  color: #fff;
}

.status-tag.warning {
  background-color: #e6a23c;
  color: #fff;
}

.status-tag.info {
  background-color: #909399;
  color: #fff;
}
</style> 